<?php

namespace App\Jobs;

use App\Jobs\Job;
use App\Facades\DeviceService;
use App\Facades\UserManager;
use Cache;
use Carbon\Carbon;
use Mail;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendTemplateMessage extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    private $_data;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->_data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $userInfos = UserManager::getUserInfoByDeviceCode($this->_data['deviceCode']);
        if(!is_null($userInfos)){
            foreach($userInfos as $userInfo){
                if(Cache::has($this->_data['deviceCode'].'remind')){
                    $remindCache = Cache::get($this->_data['deviceCode'].'remind');
                }else{
                    $remindCache = [
                    0 => [],
                    20 => [],
                    45 => [],
                    ];
                }
                if($this->_data['residualFlow'] > 20 && !in_array($userInfo->open_id, $remindCache[45])){
                    DeviceService::sendTemplateMessage($userInfo, $this->_data);
                    $remindCache[45][] =$userInfo->open_id;
                }else if($this->_data['residualFlow'] > 0 && !in_array($userInfo->open_id, $remindCache[20])){
                    DeviceService::sendTemplateMessage($userInfo, $this->_data);
                    $remindCache[20][] =$userInfo->open_id;
                }else if($this->_data['residualFlow'] == 0 && !in_array($userInfo->open_id, $remindCache[0])){
                    DeviceService::sendTemplateMessage($userInfo, $this->_data);
                    $remindCache[0][] =$userInfo->open_id;
                }
                Cache::put($this->_data['deviceCode'].'remind', $remindCache,  Carbon::now()->addMinutes(60*24*365));
            }
        }
    }

}
